const axios = require('axios');
const config = require('../config');

class GLMService {
    constructor() {
        this.client = axios.create({
            baseURL: config.GLM_BASE_URL,
            headers: {
                'Authorization': `Bearer ${config.GLM_API_KEY}`,
                'Content-Type': 'application/json'
            }
        });
    }

    async analyzeImage(base64Image) {
        try {
            const visionPrompt = `你是一个视障人士辅助AI，请按照以下步骤分析图片：
                                        1. 详细描述图片内容（适合视障人士理解的描述方式）
                                        2. 分析图片中存在的潜在危险要素，评估对视力障碍者的风险等级
                                        3. 按照以下JSON格式响应：
                                        {
                                        "description": "自然语言描述",
                                        "safety_analysis": {
                                            "is_dangerous": "是否危险?危险返回true，安全返回false",
                                            "danger_level": "low/medium/high",
                                            "reasons": ["危险原因1", "危险原因2"],
                                            "safety_tips": ["具体安全建议1", "具体安全建议2"]
                                        }
                                        }`

            const response = await this.client.post('/chat/completions', {
                model: "glm-4v-flash",
                messages: [{
                    role: "user",
                    content: [
                        { type: "text", text: visionPrompt },
                        { type: "image_url", image_url: { url: `data:image/jpeg;base64,${base64Image}`, detail: "high" } }
                    ]
                }],
                response_format: { type: "json_object" } // 强制JSON输出
            });

            return this.parseResponse(response.data);
        } catch (error) {
            console.error('GLM API 错误:', error.response?.data || error.message);
            throw new Error('AI分析服务暂不可用');
        }
    }

    parseResponse(responseData) {
        try {
            const result = JSON.parse(responseData.choices[0].message.content);

            // 数据校验
            // if (!result.safety_analysis?.is_dangerous) {
            //     throw new Error('缺少安全分析字段');
            // }

            return {
                description: result.description,
                isDangerous: result.safety_analysis.is_dangerous,
                dangerLevel: result.safety_analysis.danger_level || 'unknown',
                safetyTips: result.safety_analysis.safety_tips || [],
                safetyReasons: result.safety_analysis.reasons || [],
            };
        } catch (e) {
            console.error('响应解析失败:', e);
            return {
                description: "图片分析成功，但结果解析异常",
                isDangerous: false,
                safetyTips: []
            };
        }
    }
}

module.exports = new GLMService();